package admission.ecnu.mainservlet;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import admission.ecnu.interfaces.IRnsService;


public class ServiceManager {
	
	private static HashMap<String, IRnsService> serviceManager = null;
	
	public static void init(RnsContext context){
		serviceManager = new HashMap<String, IRnsService>();
		String path = context.getRequest().getSession().getServletContext().getRealPath("");
		path += "/xml/initservice.xml";

		try {
			DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); 
			DocumentBuilder db = dbf.newDocumentBuilder();
			Document document = db.parse(new File(path));
			NodeList services = document.getElementsByTagName("service");
			for(int i = 0 ; i < services.getLength(); ++i){
				String name = services.item(i).getChildNodes().item(1).getTextContent();
				String classname = services.item(i).getChildNodes().item(3).getTextContent();
				serviceManager.put(name, (IRnsService) Class.forName(classname).newInstance());
			}
		} catch (ParserConfigurationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SAXException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InstantiationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} 
	}
	
	public static IRnsService getService(RnsContext context){
		IRnsService service = null;
		
		if(null == serviceManager){
			init(context);
		}
		service = serviceManager.get(context.getServiceName());
		
		return service;
	}
}
